package com.yehuo.app.schedule;


import com.yehuo.app.entity.Order;
import com.yehuo.app.entity.OrderRedPacket;
import com.yehuo.app.entity.Wallet;
import com.yehuo.app.mapper.OrderMapper;
import com.yehuo.app.mapper.OrderRedPacketMapper;
import com.yehuo.app.mapper.WalletMapper;
import java.util.Date;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.Executors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component
public class DelayQueueManager implements CommandLineRunner {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderRedPacketMapper orderRedPacketMapper;
    @Autowired
    private WalletMapper walletMapper;
    private final Logger logger = LoggerFactory.getLogger(DelayQueueManager.class);
    private DelayQueue<DelayTask> delayQueue = new DelayQueue();

    public DelayQueueManager() {
    }

    public void put(DelayTask task) {
        this.logger.info("加入延时任务：{}", task);
        this.delayQueue.put(task);
    }

    public boolean remove(DelayTask task) {
        this.logger.info("取消延时任务：{}", task);
        return this.delayQueue.remove(task);
    }

    public boolean remove(String taskid) {
        TaskBase taskBase = new TaskBase();
        taskBase.setIdentifier(taskid);
        return this.remove(new DelayTask(taskBase, 0L));
    }

    public void run(String... args) throws Exception {
        this.logger.info("初始化延时队列");
        Executors.newSingleThreadExecutor().execute(new Thread(this::excuteThread));
    }

    private void excuteThread() {
        while(true) {
            try {
                DelayTask task = this.delayQueue.take();
                this.processTask(task);
            } catch (Exception var2) {
                var2.printStackTrace();
            }
        }
    }

    private void processTask(DelayTask task) {
        String identifier = task.getData().getIdentifier();
        this.logger.info("开始执行延时任务：", identifier);
        if (task.getData() instanceof Order) {
            Order currentOrder = (Order)task.getData();
            currentOrder = this.orderMapper.selectById(currentOrder.getId());
            if (currentOrder.getStatus() == 0 && identifier.startsWith("noPayOrder")) {
                this.logger.info("执行延时任务noPayOrder：{}", task);
                currentOrder.setStatus(4);
                currentOrder.setUpdateTime(new Date());
                currentOrder.setEndTime(new Date());
                this.orderMapper.updateById(currentOrder);
            } else if (currentOrder.getStatus() == 1 && identifier.startsWith("payOrder")) {
                this.logger.info("执行延时任务payOrder：{}", task);
                currentOrder.setStatus(4);
                currentOrder.setUpdateTime(new Date());
                currentOrder.setEndTime(new Date());
                this.orderMapper.updateById(currentOrder);
                Wallet wallet = this.walletMapper.selectByUserId(currentOrder.getUserId());
                this.walletMapper.updateAddAmount(wallet.getId(), currentOrder.getAmount(), new Date());
            }
        } else if (task.getData() instanceof OrderRedPacket) {
            OrderRedPacket orderRedPacket = (OrderRedPacket)task.getData();
            orderRedPacket = this.orderRedPacketMapper.selectById(orderRedPacket.getId());
            if (orderRedPacket.getState() == 0) {
                orderRedPacket.setState(1);
                orderRedPacket.setUpdateTime(new Date());
                this.orderRedPacketMapper.updateById(orderRedPacket);
                Order order = this.orderMapper.selectById(orderRedPacket.getOrderId());
                Wallet wallet = this.walletMapper.selectByUserId(order.getUserId());
                this.walletMapper.updateAddAmount(wallet.getId(), orderRedPacket.getAmount(), new Date());
            }
        }

        this.logger.info("开始执行延时任务：", task.getData().getIdentifier());
    }
}
